package com.xpgk.app.login;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import org.apache.commons.codec.binary.Base64;

import com.jfinal.aop.Before;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.xpgk.annotation.Service;
import com.xpgk.mvc.base.BaseService;
import com.xpgk.mvc.bentryRegister.Customer;
import com.xpgk.mvc.bentryRegister.CustomerDetail;
import com.xpgk.tools.security.ToolPbkdf2;

@Service(name = AppLoginService.serviceName)
public class AppLoginService extends BaseService{
	
	private static final Log log = Log.getLog(AppLoginService.class);

	public static final String serviceName = "appLoginService";
	
	
	@Before(Tx.class)
	public Customer regist(Customer customer, CustomerDetail cusDetail){
		try {
			// 密码加密
			byte[] salt = ToolPbkdf2.generateSalt();// 密码盐
			byte[] encryptedPassword = ToolPbkdf2.getEncryptedPassword(customer.getStr(Customer.column_password), salt);
			customer.set(Customer.column_salt, Base64.encodeBase64String(salt));
			customer.set(Customer.column_password, Base64.encodeBase64String(encryptedPassword));
			
			// 保存用户
			customer.set(Customer.column_state, "1");
			customer.save();
			
			if(null != cusDetail){
				cusDetail.set(CustomerDetail.column_customerIds, customer.getPKValue());
				cusDetail.save();
			}

		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("保存用户密码加密操作异常", e);
		} catch (InvalidKeySpecException e) {
			throw new RuntimeException("保存用户密码加密操作异常", e);
		} catch (Exception e) {
			throw new RuntimeException("保存用户异常", e);
		}
		return customer;
	}

}
